<template>
	<view class="wifiPage">
		<view class="wifi-top">
			<view class="wifi-top-title">
				选择wifi
			</view>
			<view class="wifi-top-surport">
				此设备只支持使用2.4Hz Wifi连接使用
			</view>
			<view class="wifi-top-surport">
				Wifi名称仅支持英文字符数字
			</view>
			<view class="wifi-top-surport" v-if="errorMsg" style="color: red;">
				{{errorMsg}}
			</view>
		</view>
		<up-form :model="form" ref="formRef" :rules="rules">
			<view class="wifi-center">

				<view class="wifi-center-name">

					<up-form-item prop="name" placeholder="请选择wifi">
						<up-input v-model="form.name" />
					</up-form-item>

					<!-- <view class="choose-wifi-btn" @click="openWifiSettings">
						选择wifi
					</view> -->
					<view class="choose-wifi-btn" @click="openWifiList">
						选择wifi
					</view>
				</view>
				<view class="wifi-center-pass">


					<up-form-item prop="pass" placeholder="请输入密码">
						<up-input v-model="form.pass" :password="showPassword" />
					</up-form-item>

					<view class="" @click="togglePasswordType">
						<up-icon name="eye-fill" v-if="!showPassword" size="22"></up-icon>
						<up-icon name="eye-off" v-if="showPassword" size="22"></up-icon>
					</view>
				</view>
				<view class="wifi-center-rule">
					Wi-Fi密码输入错误回导致配置失败，请仔细检测Wi-Fi密码
				</view>
				<view class="wifi-center-rule">
					密码必须至少包含8个字符
				</view>

			</view>
			<u-toast ref="uToast"></u-toast>
		</up-form>
		<view class="wifi-bottom">
			<view class="wifi-bottom-btn" @click="next">
				下一步
			</view>
		</view>
		<!-- WiFi列表弹窗 -->
		<up-popup :show="showWifiList" mode="bottom" round="16" @close="showWifiList=false" closeable>
			<view class="wifi-popup">
				<view class="popup-header">
					<text class="title">选择WiFi网络</text>
				</view>
				<view class="popup-content">
					<view v-if="wifiList.length>0">
						<scroll-view scroll-y class="wifi-scroll" style="height: 600rpx;">
							<view v-for="(wifi, index) in wifiList" :key="index" class="wifi-item"
								@click="selectWifi(wifi)">
								<view class="wifi-info">
									<!-- 		      	      <text class="ssidName">wifi名称</text> -->
									<text class="ssid">{{ wifi.SSID }}</text>
								</view>
							</view>
						</scroll-view>
					</view>
				</view>
			</view>
		</up-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted
	} from 'vue';
	// 响应式表单数据
	const form = ref({
		name: '',
		pass: ''
	});
	const showPassword = ref(true);
	const togglePasswordType = () => {
		showPassword.value = !showPassword.value;
	};
	const showWifiList = ref(false);

	// 校验规则
	const rules = {
		"name": {
			required: true,
			message: '请选择wifi',
			trigger: ['blur', 'change'],
		},
		"pass": {
			required: true,
			message: '请输入密码',
			trigger: ['blur', 'change'],
		}
	}
	// 表单引用
	const formRef = ref(null);
	// 当前连接的WiFi信息
	const currentWifi = ref(null);
	const wifiList = ref([]);
	const errorMsg = ref('');
	// 获取当前wifi
	const checkPermissionAndGetWifi = async () => {
		if (typeof uni.getConnectedWifi !== 'function') {
			errorMsg.value = '当前平台不支持获取WiFi信息';
			return;
		}
		uni.startWifi({
			success: () => {
				getWifiList();
				uni.getConnectedWifi({
					success: (res) => {
						console.log(res.wifi, 'wifi信息')
						form.value.name = res.wifi.SSID || '未知WiFi';
					},
					fail: (err) => {
						console.log('获取WiFi信息失败，请检查权限和网络')
						// errorMsg.value = '获取WiFi信息失败，请检查权限和网络';
					}
				});
			},
			fail: (err) => {
				errorMsg.value = 'WiFi模块初始化失败';
			}
		});
	};
	// 打开wifi列表
	const openWifiList = async () => {
		showWifiList.value = true;
	};

	const getWifiList = async () => {
		// 检查位置授权状态
		const authSetting = await uni.getSetting();
		if (!authSetting.authSetting['scope.userLocation']) {
			uni.showModal({
				title: '位置授权',
				content: '获取WiFi列表需要开启位置授权，请前往设置开启',
				success: (res) => {
					if (res.confirm) {
						wx.authorize({
							scope: 'scope.userLocation',
							success() {
								console.log('位置授权成功！')
								getWifiList();
							},
							fail(e) {
								console.log('back', e)
								uni.showToast({
									title: '未开启位置授权，无法获取WiFi列表',
									icon: 'none'
								});
							}
						});
					}
				}
			});
		} else {
			// 已授权，直接加载WiFi列表
			wx.getWifiList({
				success(res) {
					uni.onGetWifiList((res) => {
						console.log('获取到wif列表', res);
						//去个虫
						const set = new Set();
						wifiList.value = res.wifiList.filter(wifi => {
							if (!set.has(wifi.SSID) && wifi.SSID) {
								set.add(wifi.SSID);
								return true;
							}
							return false;
						});

					})
				},
				fail(e) {
					console.log('完蛋了', e)
				}
			})
		}
	};


	const selectWifi = (wifi) => {
		form.value.name = wifi.SSID;
		//移除监听
		wx.offWifiConnected();
		showWifiList.value = false;
	};

	// 提交方法
	const next = () => {
		try {
			if (!formRef.value) {
				console.error('表单引用未正确初始化');
				return;
			}
			formRef.value.validate().then(res => {
				let encodedid = encodeURIComponent(form.value.name);
				let encodedpass = encodeURIComponent(form.value.pass);
				uni.navigateTo({
					url: `/Device/connectDevice/connectDevice?ssid=${encodedid}&pass=${encodedpass}`
				})
				// return
			}).catch(err => {
				console.log(err, '校验失败');
				// return
			})



		} catch (error) {
			console.error('验证过程发生错误:', error);
		}
	}
	// 页面挂载时获取WiFi信息
	onMounted(() => {
		checkPermissionAndGetWifi()
	})
</script>

<style lang="scss" scoped>
	@import "./chooseWifi.scss";

	::v-deep .u-form-item {
		width: 100%;
		height: 120rpx;
	}

	::v-deep .u-border {
		border: 0;

	}

	::v-deep .u-input__content__field-wrapper__field {
		line-height: 120rpx;
		font-size: 50rpx;
	}

	::v-deep .u-form-item__body {
		padding: 30rpx 0 !important;
	}

	.popup-content {
		height: calc(100% - 60rpx);

		.loading {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			height: 100%;

			text {
				margin-top: 20rpx;
				color: #999;
			}
		}

		.wifi-scroll {
			height: 100%;
		}



		.error-msg {
			color: #fa3534;
			text-align: center;
			padding: 20rpx;
			font-size: 28rpx;
		}
	}

	.wifi-item {
		width: 92%;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 25rpx 0;
		border-bottom: 1rpx solid #f5f5f5;

		.wifi-info {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.ssidName {
				font-size: 32rpx;
				margin-left: 15rpx;
			}

			.ssid {
				margin-right: 15rpx;
				font-size: 32rpx;
			}
		}

		.wifi-signal {
			display: flex;
			align-items: center;
			color: #999;
			font-size: 26rpx;

			text {
				margin-left: 8rpx;
			}
		}
	}
</style>